package cn.oniokey.waterDetection.controller;

import cn.dev33.satoken.stp.SaTokenInfo;
import cn.dev33.satoken.stp.StpUtil;
import cn.dev33.satoken.util.SaResult;
import cn.oniokey.waterDetection.domain.User;
import cn.oniokey.waterDetection.service.serviceImpl.UserServiceImpl;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;


@RestController
@RequestMapping("/user")
public class UserController {

    final
    UserServiceImpl userService;

    public UserController(UserServiceImpl userService) {
        this.userService = userService;
    }

    // 用户登录
    @RequestMapping("/login")
    public SaResult  login(@RequestBody User user) {
        User loginUser = userService.getUserByUsernameAndPassword(user.getUsername(), user.getPassword());
        if (loginUser != null) {
            StpUtil.login(user.getUsername());
            SaTokenInfo tokenInfo = StpUtil.getTokenInfo();
            return SaResult.data(tokenInfo);
        }
        return SaResult.error("登录失败!");
    }

    // 查询登录状态
    @RequestMapping("isLogin")
    public SaResult  isLogin() {
        return SaResult.ok("是否登录:" + StpUtil.isLogin());
    }

    // 查询 Token 信息
    @RequestMapping("tokenInfo")
    public SaResult tokenInfo() {
        return SaResult.data(StpUtil.getTokenInfo());
    }

    // 用户登出
    @RequestMapping("logout")
    public SaResult logout(){
        StpUtil.logout();
        return SaResult.ok();
    }

}
